package com.itic.demo.templet.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.exports.ExportExcel;
import com.itic.appbase.applications.exports.ExportExcelWithTemplet;
import com.itic.appbase.applications.files.utils.FileHelper;
import com.itic.appbase.applications.imports.ImportExcelUtil;
import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.demo.templet.service.TempletService;
import com.itic.demo.templet.persistence.model.Templet;
import com.itic.demo.templet.persistence.model.TempletExample;
import com.itic.demo.templet.persistence.model.TempletExample.Criteria;


@Controller
@RequestMapping(value="/demo/templet")
public class TempletController
     extends BaseController {
    @Autowired
    private TempletService templetService;

    @Autowired
	protected OutCommonService outCommonService;
    
    //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
    private static final String MODEL_NAME_CHINA = "模板示例";//中文名
    private static final String MODEL_NAME＿ENGLISH = "templet";//英文名
    private static final String PAGE_COMMON_PATH = "/demo/templet/templet";//通用路径
    private static final String COMMON_URL = "/demo/templet/";//通用路径
    private static final String CATEGORY = "T_DM_DEMO_TEMPLET_CATEGORY";//代码表名称
    
    //导出常量
    private static final String TEMP = "bzmc";//备注名称
    private static final String DATALIST = "dataList";//数据常量
    // 返回属性黑名单
    private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "createTime", "updateTime",
            "orgCode" };


    //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
   
    /*
     * 主页面
     */
    @RequestMapping(value="/init")
    public String init(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Main";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		Templet temp = templetService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initView")
    public String initView(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		
    		Templet temp  = templetService.get(id);
    		temp.setCategory(outCommonService.getNameByCode(CATEGORY, temp.getCategory()));
    		
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"View";
    }
    
    /*
     * 导入页面
     */
    @RequestMapping(value="/initImp")
    public String initImp(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Imp";
    }
    
    
    //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(Templet templet){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = templetService.add(templet);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    
    /**
     * <p>Title:queryCondition </p>
     * <p>Description:封装查询条件 </p>
     * @param jzdw
     * @param jzdwExample
     * @return
     */
    private TempletExample queryCondition(HttpServletRequest request,Templet templet) {
    	
    	// 参数处理
        TempletExample example = new TempletExample();
        // 按创建时间倒序
        example.setOrderByClause("create_time desc");
        // 按排列号顺序
        example.setOrderByClause("reorder asc");
        
        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
      
        //过滤组织机构
        //User user = findUserSession(request);
        //criteria.andOrgCodeEqualTo(user.getOrganizationCode());
        
        // 查询条件
        if ( null != templet ) {
    	    //模糊查询
            if ( StringHelper.isNotBlank( templet.getName() ) ) {
                criteria.andNameLike("%" + templet.getName() + "%");
            }
            //类别 查询
            if( StringHelper.isNotBlank(templet.getCategory()) ){
            	criteria.andCategoryEqualTo(templet.getCategory());
            }
            
        }
        return example;
    }
    
    /**
     * 
     * @param goldType
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(Templet templet, HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        
        TempletExample example = this.queryCondition(request,templet);
        // 封装分页参数
        example = this.handlePageQuery(request, example);
        
        
        // 获取信息总条数
        int total = templetService.count(example);
        
        // 获取数据
        List<Templet> list = templetService.list(example);
        
        //结果集
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        if( list.size() > 0 ){
        	for( Templet temp : list){
        		temp.setCategory(outCommonService.getNameByCode(CATEGORY, temp.getCategory()));
        	}
            //过滤黑名单字段   
        	resultList = ValueHelper.tranList2MapList(list, ignoreProperties);
        }
        
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, total);
        resultMap.put(IticConst.DISPLAY_RECORDS, total);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, resultList);
        return resultMap;

    }
    
    /**
     * 编辑保存
     * @param templet
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(String delFileIds , Templet templet){
    
    	if( StringHelper.isNotBlank(delFileIds) ){
    		// 删除附件
    		outCommonService.deleteFiles(delFileIds);
    	}
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = templetService.edit(templet);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    

    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        if (StringHelper.isNotBlank(ids)) {
        	
            List<String> idList = Arrays.asList(ids.split(","));
            
            TempletExample example = new TempletExample();
            example.createCriteria().andIdIn(idList);
          
            Templet templet = new Templet();
            result = templetService.deleteByExample(templet, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        //删除一个
        /*
        if( StringHelper.isNotBlank(id) ){
            Templet templet = new Templet();
            templet.setId(id);
            result = templetService.delete(templet);
        }
        */
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * exp
     * 
     */
    @RequestMapping(value = "/exp")
    @ResponseBody
    public void exp(HttpServletRequest request, HttpServletResponse response,Templet temp) {
    	 try {        	
         	 // 参数处理
    		 TempletExample example=new TempletExample();         
             example = this.queryCondition(request,temp);           
             // 获取数据
             List<Templet> list = templetService.list(example);        
             //导出
             Map<String, Object> exportMap = new HashMap<String, Object>();
             exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
             exportMap.put(DATALIST, list);
             ExportExcel exportExcel = new ExportExcelWithTemplet();
             exportExcel.exportExcel(exportMap, request, response);
             
         } catch (Exception e) {
        	 throw new RuntimeException("[TempletController | exp 模板示例导出异常]");
         } 
    }
    
    
    /**
     * exp
     * 
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/imp")
    @ResponseBody
    public Map<String, String> imp(HttpServletRequest request,String fileId) {
    	Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();
    	 try {
             // 获取Excel解析数据
             Map<String, Object> excelDataMap = new HashMap<String, Object>();
             String filePath = outCommonService.getFilePath(fileId);
             if (StringHelper.isNotBlank(filePath)) {
            	 excelDataMap = ImportExcelUtil.readValue( new File(FileHelper.getRootDir(), filePath), MODEL_NAME＿ENGLISH );
             }
             // 获取验证错误List集合
             List<String> errorInfoList =  (List<String>) excelDataMap.get("error");
             // 获取对象组成的List集合
             List<Templet> dataList = (List<Templet>) excelDataMap .get("data");                 
             if (errorInfoList != null && errorInfoList.size() > 0) {
                 // 处理错误信息，返回前台
                 result = "error";
                 resultMap.put(IticConst.DATA, "ERROR");
                 request.getSession().setAttribute("ExcelImpError",
                         errorInfoList);
             } else if (dataList != null && dataList.size() > 0) {
                 //处理excel数据
            	 result = templetService.imp(request,dataList);
             }
         
         } catch (Exception e) {
        	 throw new RuntimeException("[TempletController | imp 模板示例导入异常]");
         } 
    	 resultMap.put(IticConst.RESULT, result);
         return resultMap; 
    }
    

}